package com.atgugu.springcloud.controller;



import com.atgugu.springcloud.entities.PayDTO;
import com.atgugu.springcloud.resp.ResultData;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class OrderController {

        public static final  String PaymentStr_URL = "http://cloud-payment-service"; //先写死，硬编码

        @Resource
        private RestTemplate restTemplate;

        @GetMapping("/consumer/pay/add")
        public ResultData addOrder(@RequestBody PayDTO payDTO) {
                return restTemplate.postForObject(PaymentStr_URL+"/pay/add", payDTO, ResultData.class);
        }

        @GetMapping("/consumer/pay/get/{id}")
        public ResultData getOrder(@PathVariable("id") Integer id){
                return restTemplate.getForObject(PaymentStr_URL+"/pay/get/"+id, ResultData.class,id);
        }


        @GetMapping("/consumer/pay/update")
        public ResultData updateOrder( PayDTO payDTO){
               restTemplate.put(PaymentStr_URL + "/pay/update", payDTO);
               return ResultData.success("更新成功");
        }

        @GetMapping("/consumer/pay/delete/{id}")
        public ResultData deleteOrder(@PathVariable("id") Integer id){
              restTemplate.delete(PaymentStr_URL+"/pay/delete/"+id,ResultData.class,id);
              return ResultData.success("删除成功");
        }

        @GetMapping("/consumer/pay/get/info")
        private String getInfoByConsul(){
                return restTemplate.getForObject(PaymentStr_URL+"/get/info",String.class);
        }

        @Resource
        private DiscoveryClient discoveryClient;
        @GetMapping("/consumer/discovery")
        public String discovery(){
               List<String> services = discoveryClient.getServices();
               for (String service : services) {
                   System.out.println("service:"+service);
               }
                System.out.println("================================================");
                List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
                for (ServiceInstance element : instances) {
                        System.out.println(element.getServiceId()+"\t"+element.getHost()+"\t"+element.getPort()+"\t"+element.getUri());
                }

                return instances.get(0).getServiceId()+":"+instances.get(0).getPort();
        }



}
